// pages/product/product-detail/index.js
const util = require("../../../../utils/util.js");
const wxParser = require("./../../../../utils/wxParser/index");

Page({
    data: {
        cartNum: 0,
        current_num: 1,
        color: wx.getExtConfigSync().color,
        rgbColor: util.colorRgb(wx.getExtConfigSync().color),
        showSku: false,
        type:0,
        skuHeight: util.rpxToPx(-694) // 购物车弹窗高度
    },
    onLoad: function (options) {
        this.data.id = options.id;
        //通过二维码进入商品首页,添加分销关系
        if(options.pid){
          this.addFxUser(options.pid)
        }

        // 判断是否为分销商；
        this.isFxUser();
    },
    onShow: function () {
        if (this.data.id) {
            this.getDetail(this.data.id);
        }
        const cart_data = wx.getStorageSync('cart-data') ? JSON.parse(wx.getStorageSync('cart-data')) : [];
        this.setData({
            cartNum: cart_data.length
        })
    },
    isFxUser:function(){
      wx.doodoo.fetch('/fx/api/user/isFxUser').then(res => {
        const data = res.data.data;
        console.log("data-->", data);
        if (data && Number(res.data.errcode) === 0) {
           wx.setStorageSync("fxUser", data)
        }

      })
    },
    addFxUser:function(pid){
      wx.doodoo.fetch(`/fx/api/product/addNewUser?pid=${pid}`).then(res=>{
          console.log("添加新的分销关系成功");
      })
    },
    getDetail(id) {
        wx.doodoo.fetch(`/shop/api/shop/product/product/info?id=${id}`).then(res => {
            if (res && res.data.errmsg == 'ok') {
                this.defaultSKU(res.data.data);
                this.init(res.data.data.detail);
                if(res.data.data.type==1){
                  this.setData({
                    type:1
                  })
                }
            }
        })
    },
    // 设置默认规格
    defaultSKU(detailInfo) {
        detailInfo.num = 1;
        let select_sku = {};
        if (detailInfo.sku_status && detailInfo.skuData && detailInfo.skuData.length) {
            detailInfo.skuData.forEach(val => {
                if (val.child && val.child.length) {
                    val.child.forEach((sku, i) => {
                        sku.is_select = 0;
                    })
                    val.child[0].is_select = 1;
                }
            })
            let sku_ids = [];
            detailInfo.skuData.forEach(val => {
                if (val.child && val.child.length) {
                    val.child.forEach(sku => {
                        if (sku.is_select) {
                            sku_ids.push(sku.id);
                        }
                    })
                }
            })
            sku_ids = sku_ids.join('-');
            detailInfo.sku.forEach(val => {
                if (val.sku_ids == sku_ids) {
                    select_sku = val;
                }
            })
            detailInfo.select_sku = select_sku;
        } else {
            detailInfo.select_sku = select_sku;
        }
        this.setData({
            detailInfo: detailInfo
        })
    },
    iconBtn(e) {
        const type = Number(e.currentTarget.id); // 0：客服 1：收藏 2：购物车
        if (type == 0) {
            console.log('kefu', e);
        }
        if (type == 1) {
            const detailInfo = e.currentTarget.dataset.data;
            if (!detailInfo.collection.id) {
                wx.doodoo.fetch(`/shop/api/shop/collection/add?id=${detailInfo.id}`).then(res => {
                    if (res && res.data.errmsg == 'ok') {
                        wx.showToast({
                            title: "收藏成功"
                        });
                        this.getDetail(detailInfo.id);
                    }
                });
            }
            if (detailInfo.collection.id) {
                wx.doodoo.fetch(`/shop/api/shop/collection/del?id=${detailInfo.collection.id}`).then(res => {
                    if (res && res.data.errmsg == 'ok') {
                        wx.showToast({
                            title: "取消收藏"
                        });
                        this.getDetail(detailInfo.id);
                    }
                });
            }
        }
        if (type == 2) {
            wx.switchTab({
                url: '/pages/shop/cart/index'
            })
        }
    },
    hideModal() {
        let _skuHeight = this.data.detailInfo.sku_status ? this.data.skuHeight : util.rpxToPx(-450);
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: 'linear'
        })
        animation.translateY(0).step();
        this.setData({
            animationData: animation.export()
        })
        setTimeout(() => {
            animation.translateY(_skuHeight).step();
            this.setData({
                animationData: animation.export(),
                showSku: false
            })
        }, 200)
    },
    showModal(e) {
        // 0：加入购物车  1：立即购买
        let _skuHeight = this.data.detailInfo.sku_status ? this.data.skuHeight : util.rpxToPx(-450);
        this.data.is_buynow = Number(e.currentTarget.id);
        let animation = wx.createAnimation({
            duration: 200, // 动画持续时间
            timingFunction: 'linear' // 定义动画效果，当前是匀速
        })
        animation.translateY(0).step();
        this.setData({
            animationData: animation.export(), // 通过export()方法导出数据
            showSku: true
        })
        // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
        setTimeout(() => {
            animation.translateY(_skuHeight).step();
            this.setData({
                animationData: animation.export()
            })
        }, 200)
    },
    buyNowOrAddCart(e) {
        this.hideModal();
        // 0：加入购物车  1：立即购买
        let detailInfo = e.detail;
        detailInfo.is_select = 0;
        if (this.data.is_buynow) {
            let save_now = [];
            detailInfo.is_select = 1;
            save_now.push(detailInfo);
            wx.setStorageSync('save-now', JSON.stringify(save_now));
            wx.navigateTo({
                url: `../../order/order-add/index`
            })
        } else {
            let cart_data = wx.getStorageSync('cart-data') ? JSON.parse(wx.getStorageSync('cart-data')) : [];
            if (cart_data.length) {
                let sameData = {};
                let index = 0;
                cart_data.forEach((product, i) => {
                    if (product.id == detailInfo.id && product.select_sku.id == detailInfo.select_sku.id) {
                        sameData = product;
                        cart_data.splice(i, 1);
                        index = i;
                    }
                });
                if (sameData.id) {
                    sameData.num += detailInfo.num;
                    cart_data.splice(index, 0, sameData);
                } else {
                    cart_data.push(detailInfo);
                }
            } else {
                cart_data.push(detailInfo);
            }
            wx.setStorageSync('cart-data', JSON.stringify(cart_data));
            this.setData({
                cartNum: cart_data.length
            })
        }
    },
    Share(e) {
        wx.navigateTo({
            // type=1 通过商品详情进入推广图片
            url: `/pages/shop/share/share?type=1&data=${e.currentTarget.dataset.data}`
        });
    },
    onShareAppMessage: function (e) {
        const data = this.data.detailInfo;
        let url = `pages/product/product-detail/index?detail_id=${data.id}`;
        return {
            title: data.name,
            path: url
        };
    },
    init: function (newVal) {
        wxParser.parse({
            bind: "richText",
            html: newVal,
            target: this,
            enablePreviewImage: false, // 禁用图片预览功能
            tapLink: url => {
                // 点击超链接时的回调函数
                // url 就是 HTML 富文本中 a 标签的 href 属性值
                // 这里可以自定义点击事件逻辑，比如页面跳转
                // wx.navigateTo({
                //     url
                // });
            }
        });
    }
})